package com.mata.worktime.handler;

import com.mata.worktime.exception.BaseException;
import com.mata.worktime.vo.ResultVO;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mata.worktime.util.security.PermissionUtils;

import org.springframework.validation.BindException;

import java.util.List;


/**
 * 全局异常处理器
 *
 * @author earthchen
 * @date 2018/9/26
 **/
@ControllerAdvice
public class DefaultExceptionHandler
{

    private static final Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    /**
     * 权限校验失败
     */
    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public ResultVO handleAuthorizationException(AuthorizationException e)
    {
        log.error(e.getMessage(), e);
        return ResultVO.error(1, PermissionUtils.getMsg(e.getMessage()));
    }

    /**
     * 请求方式不支持
     */
    @ResponseBody
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResultVO handleException(HttpRequestMethodNotSupportedException e)
    {
        log.error(e.getMessage(), e);
        return ResultVO.error(1, "不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResultVO notFount(RuntimeException e)
    {
        log.error("运行时异常:", e);
        return ResultVO.error(1, "运行时异常:" + e.getMessage());
    }

    /**
     * 系统异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return ResultVO.error(500, "服务器错误，请联系管理员");
    }

    /**
     * 处理绑定异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ResultVO handleBindException(BindException ex)
    {
        List<ObjectError> errors = ex.getAllErrors();
        ObjectError error = errors.get(0);
        String msg = error.getDefaultMessage();
        return ResultVO.error(400, String.format("参数错误--", msg));
    }

    /**
     * 处理基类异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BaseException.class)
    public ResultVO handleBaseException(BaseException e)
    {
        log.error(e.getMessage(), e);
        return ResultVO.error(e.getCode(), e.getMessage());
    }
}
